<template>
  <div class="app-container">
    <el-form v-if="executeQuery" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="广告标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入广告标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="创建日期" prop="creationDate">
        <el-date-picker clearable
          v-model="queryParams.creationDate"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择创建日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="失效日期" prop="expirationDate">
        <el-date-picker clearable
                        v-model="queryParams.expirationDate"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择失效日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部">
          <el-option value="1" label="生效中"></el-option>
          <el-option value="2" label="已下架"></el-option>
          <el-option value="3" label="已过期"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推送时间" prop="pushTime">
        <el-date-picker clearable
                        v-model="queryParams.pushTime"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择推送时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="flex-container">
      <el-button icon="el-icon-search"  @click="executeQuery =true" plain >高级搜索</el-button>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['launch:advertisement:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['launch:advertisement:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['launch:advertisement:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['launch:advertisement:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="advertisementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" >
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)" style="color:#6a9eff;text-decoration: underline;">{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="广告标题" align="center" prop="title" />
      <el-table-column label="时长/s" align="center" prop="duration" />
      <el-table-column label="推送时间" align="center" prop="pushTime" width="180"/>

      <el-table-column label="失效日期" align="center" prop="expirationDate" width="180"/>

      <el-table-column label="创建日期" align="center" prop="creationDate" width="180"/>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
         {{scope.row.status=='1'?'生效中':scope.row.status=='2'?'已下架':'已过期'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <span class="ellipsis" @click="toggleButton"><strong>···</strong></span><br/>


            <el-button v-show="showButton" size="mini" type="text" icon="el-icon-s-promotion"
                       @click="upPushTime(scope.row)" >
              重新推送
            </el-button><br/>
            <el-button v-show="showButton" size="mini" type="text" icon="el-icon-zoom-out"
                       @click="downPush(scope.row)"
                       v-hasPermi="['launch:advertisement:remove']">
              下架
            </el-button><br/>
            <el-button v-show="showButton" size="mini" type="text"
                       icon="el-icon-circle-check"
                       @click="upPush(scope.row)"
                       v-hasPermi="['launch:advertisement:remove']">
              上架
            </el-button><br/>
            <el-button v-show="showButton" size="mini" type="text" icon="el-icon-delete"
                       @click="del(scope.row)"
                       v-hasPermi="['launch:advertisement:remove']">
              删除
            </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="提示" :visible.sync="open1" width="500px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules" label-width="80px">
        <i class="el-icon-info" style="color: #1c84c6;font-size: 24px;margin-left: 50px" ></i>
        <span style="font-size: 10px;margin-left: 5px;color: #1e1e1e">您确定重新推送该广告吗？请设置推送时间～</span>
        <el-form-item  prop="pushTime">
          <el-date-picker
              v-model="form1.pushTime"
              type="datetime"
              placeholder="年/月/日--:--"
              value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker><br/>
          <span style="color: #8c939d;font-size: 10px">推送时间必须大于当前时间</span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改智能柜分屏广告对话框 -->

    <!--:action="videoUpload.url" 代表调取后台视频上传的方法路径-->
    <!--:headers="videoUpload.headers" 代表访问的token验证，配置错的话上传方法访问受阻-->
    <!--:before-upload="beforeUploadVideo" 代表上传前回调，进行验证是否符合规定的要求-->
    <!--:on-progress="uploadVideoProcess" 代表上传实时进度条-->
    <!--:on-success="handleVideoSuccess" 代表上传成功后的回调，会返回上传成功后该视频的存储路径-->

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入广告标题" />
        </el-form-item>
        <el-form-item label="广告视频" prop="video" >
          <el-upload class="avatar-uploader el-upload--text" :headers="videoUpload.headers" :action="videoUpload.url" :show-file-list="false"
                     accept=".mp4"  :on-success="handleVideoSuccess"  :before-upload="beforeUploadVideo" :on-progress="uploadVideoProcess">

            <!--视频区域，:src里面存放视频上传成功后的存储地址-->
            <video v-if="this.showVideoPath !='' && !videoFlag"  :src="videoUpload.url2 + this.showVideoPath"  class="avatar video-avatar" controls="controls">
              您的浏览器不支持视频播放
            </video>

            <!-- 变量showVideoPath如果不存在，就不显示，存在就显示视频 -->
            <i v-else-if="this.showVideoPath =='' && !videoFlag" class="el-icon-plus avatar-uploader-icon">
            </i>
            <!--上传进度条区域-->
            <el-progress :stroke-width="10" class="progressType" v-if="videoFlag == true"
                         type="circle" :percentage="videoUploadPercent" style="margin-top:30px;">
            </el-progress>

            <!--此为视频点击上传按钮 isShowUploadVideo代表按钮显示与否-->
            <el-button class="video-btn" slot="trigger" size="small" v-if="isShowUploadVideo" type="primary">点击上传视频</el-button>
          </el-upload>
        </el-form-item>
        <!--form.courseUrl 代表成功上传返回的视频路径赋值给表单的这个属性，随后通过方法提交保存在对应的表中-->
        <el-form-item  style="position: relative ;">
          <el-input type="hidden" v-model="form.video" readonly class="noAlert" placeholder="" />
        </el-form-item>

          <el-form-item label="是否需要跟进" prop="pushMethod">
            <el-radio-group v-model="form.pushMethod">
              <el-radio  :label="1" >即时推送</el-radio>
              <el-radio  :label="2" >定时推送</el-radio>
            </el-radio-group>
          </el-form-item>
        <el-form-item label="推送时间" prop="pushTime">
          <el-date-picker clearable
                          v-model="form.pushTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择推送时间">
          </el-date-picker><span style="color: #97a8be">推送时间必须大于当前时间</span>
        </el-form-item>
        <el-form-item label="失效日期" prop="expirationDate">
          <el-date-picker clearable
                          v-model="form.expirationDate"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择失效日期">
          </el-date-picker><span style="color: #97a8be">失效时间必须大于当前时间</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAdvertisement, getAdvertisement, delAdvertisement, addAdvertisement, updateAdvertisement,upPushStatus,downPushStatus} from "@/api/launch/advertisement";

import { getToken } from "@/utils/auth";
import { MessageBox } from 'element-ui'
export default {
  name: "Advertisement",
  data() {
    return {
      executeQuery:false,
      showButton:false,
      //拿到当前环境的请求前缀
      videoUpload:{
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/launch/advertisement/uploadVideo",
        url2: process.env.VUE_APP_BASE_API,
      },
      showVideoPath: "",
      uploadUrl:"",//你要上传视频到你后台的地址
      videoFlag:false , //是否显示进度条
      videoUploadPercent:"", //进度条的进度，
      isShowUploadVideo:false, //显示上传按钮
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 智能柜分屏广告表格数据
      advertisementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        pushTime: null,
        expirationDate: null,
        creationDate: null,
        status: null,
      },
      // 表单参数
      form: {},
      form1:{},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "广告标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  methods: {
    downPush(row){
      const id=row.id;
      MessageBox.confirm('您确定要下架/上架/删除该广告吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 在这里执行删除操作
        downPushStatus(id).then(response=>{
          this.$message.success("下架成功");
          this.getList();
        })
      }).catch(() => {
        // 取消操作时的逻辑（如果有需要，可以在这里添加）
      });
    },
    upPush(row) {
      const id=row.id;
      MessageBox.confirm('您确定要下架/上架/删除该广告吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 在这里执行删除操作
        upPushStatus(id).then(response=>{
          this.$message.success("上架成功");
          this.getList();
        })
      }).catch(() => {
        // 取消操作时的逻辑（如果有需要，可以在这里添加）
      });
    },
    del(row){
      const id=row.id;
      MessageBox.confirm('您确定要下架/上架/删除该广告吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 在这里执行删除操作
        delAdvertisement(id).then(response=>{
          this.$message.success("删除成功");
          this.getList();
        })
      }).catch(() => {
        // 取消操作时的逻辑（如果有需要，可以在这里添加）
      });
    },
    upPushTime(row) {
      const id = row.id || this.ids
      getAdvertisement(id).then(response => {
        this.form1= response.data;
        this.open1 = true;
        this.title = "提示";
      });
    },
    submitForm1() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form1 != null) {
            updateAdvertisement(this.form1).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open1 = false;
              this.getList();
            });
          }
        }
      });
    },
    toggleButton() {
      this.showButton =!this.showButton;
    },
    handleDetail(row) {
      const id=row.id
      this.$router.push({path:"/launch/advertisement/details/role/"+id})
    },
      //上传前回调
      beforeUploadVideo (file) {
        const isLt1024M = (file.size / 1024 / 1024) < 1024;
        this.form.videoSize = file.size / 1024 / 1024;
        //判断是不是MP4格式视频
        if (['video/mp4'].indexOf(file.type) != 0) {
          this.$message.error('请上传正确的视频格式');
          return false;
        }
        //单个视频大小限制在1024M以内
        if (!isLt1024M ) {
          this.$message.error('上传视频大小不能超过1024MB哦!');
          return false;
        }
        this.isShowUploadVideo = false;
      },

      //进度条
      uploadVideoProcess (event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = file.percentage.toFixed(0) * 1;
      },

      //上传成功回调
      handleVideoSuccess (res, file) {
        this.isShowUploadVideo = true;
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        if(res !=""){
          this.showVideoPath = res;
          this.form.video = res;
        } else {
          this.$message.error('视频上传失败，请重新上传！');
        }
      },

    /** 查询智能柜分屏广告列表 */
    getList() {
      this.loading = true;
      listAdvertisement(this.queryParams).then(response => {
        this.advertisementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel1() {
      this.open1 = false;

    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        duration: null,
        pushTime: null,
        expirationDate: null,
        creationDate: null,
        status: null,
        video: null,
        pushMethod: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAdvertisement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改智能柜分屏广告";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAdvertisement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAdvertisement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除智能柜分屏广告编号为"' + ids + '"的数据项？').then(function() {
        return delAdvertisement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('launch/advertisement/export', {
        ...this.queryParams
      }, `advertisement_${new Date().getTime()}.xlsx`)
  }
  },
};
</script>
<style scoped>
.flex-container {
  display: flex;
  justify-content: center;
}
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px !important;
    position: relative !important;
    overflow: hidden !important;
  }
  .avatar-uploader .el-upload:hover {
    border: 1px dashed #d9d9d9 !important;
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 300px;
    height: 178px;
    display: block;
  }
</style>




